const Article = require('../../models/system/article');
const NavInfo = require('../../models/system/nav')

exports.home = async (req, res, next) => {
  try {
    const navInfo = await NavInfo.find({status: 1}).sort({order: 1})
    if(!navInfo) return res.render('404')
    res.render('index',{navInfo})
  } catch (error) {
    next(error)
  }
}

exports.getList = async (req, res, next) => {
  try {
    const { page=1, pageSize=10 } = req.query;
    let type = req.params.str
    // 总条数
    // const count = await Article.countDocuments({});
    const articleList = await Article.find({labelType: type}).skip(pageSize*(page-1)).limit(pageSize).sort({_id: -1});
    const navInfo = await NavInfo.find({status: 1}).sort({ order: 1 })
    const newList = await Article.find({labelType: type}).skip(0).limit(pageSize).sort({_id: -1});
    const hotList = await Article.find({hot: 1}).skip(0).limit(pageSize).sort({_id: -1});
    // 总页数
    let total = Math.ceil(Number(articleList.length) / Number(pageSize));
    if(!articleList.length){
      res.render('404')
      return
    }
    res.render('list',{
      list: articleList,
      page: Number(page),
      total,
      newList,
      hotList,
      navInfo
    })
  } catch (error) {
    next(error)
  }
}

exports.getDetail = async (req, res, next) => {
  try {
    const { id } = req.params;
    const navInfo = await NavInfo.find({status: 1}).sort({order: 1})
    const detailInfo = await Article.findById({ _id: JSON.parse(id) });
    console.log(detailInfo.content)
    const newList = await Article.find().skip(0).limit(10).sort({_id: -1});
    const hotList = await Article.find({hot: 1}).skip(0).limit(10).sort({_id: -1});

    await Article.updateOne({ _id: JSON.parse(id) },{"$inc":{'watch':1}})
    if(!detailInfo){
      res.render('404')
      return
    }
    res.render('detail',{
      detailInfo,
      newList,
      hotList,
      navInfo,
    })
  } catch (error) {
    next(error)
  }
}

// 阅读量
